const router = require('koa-router')();
const cc = require('../conCtl');
const js = require('../jsCtl');
const wc = require('../wechatCtl');

/**
@hostpath = http://127.0.0.1/client/wechatSDK
 */

/* get 用于微信token验证 */
router.get('/', async c => {
    cc.log("========= wechat token check begin");
    let signature = req.query.signature,
        timestamp = req.query.timestamp,
        nonce = req.query.nonce,
        echostr = req.query.echostr;

    let
        tmp = [token, timestamp, nonce].sort().join(""),
        currSign = crypto.createHash("sha1").update(tmp).digest("hex");
    cc.log("========= wechat token check", { signature: signature, currSign: currSign });

    if (currSign != signature) {
        cc.send(c, echostr);
    } else {
        js.throwObj("It is not from wechat");
    }
});

/* get /jssdk 用于页面wx.config权限注入的内容请求 */
router.get('/jssdk/:clientUrl', async c => {
    let clientUrl = decodeURIComponent(c.params.clientUrl);
    let token = await wc.get_jsapi_ticket();
    cc.log(token, clientUrl);
    let result = wc.sign(token, clientUrl);
    cc.send(c, result);
});



module.exports = router;